package ar.edu.unlp.info.cptn.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import ar.edu.unlp.info.cptn.model.Asignatura;
import ar.edu.unlp.info.cptn.service.PersonaService;
import ar.edu.unlp.info.cptn.validator.CursadaValidator;

@Controller
@RequestMapping (value = "/cursada")
public class CursadaController {
	
	@Autowired
	PersonaService service;

	@RequestMapping(value="/crear", method = RequestMethod.GET)
    public ModelAndView crear() {
		ModelAndView mav = new ModelAndView();
		mav.addObject("cursada",new Asignatura());
		mav.setViewName("formulario-cursada");
		return mav;
	}
	
	@RequestMapping(value="/guardar", method = RequestMethod.GET)
	public String guardar(@ModelAttribute(value="cursada") Asignatura asignatura, BindingResult result){
		CursadaValidator validator = new CursadaValidator();
		validator.validate(asignatura, result);
		if (result.hasErrors()){
			return "formulario-cursada";
		}else{
			service.guardar(asignatura);
	        return "redirect:/persona/ver/"+asignatura.getId();
		}
	}
	
	@RequestMapping(value="/ver/{identificador}", method = RequestMethod.GET)
	public ModelAndView verFicha(@PathVariable Long identificador){
		Asignatura asignatura = (Asignatura) service.get(Asignatura.class,identificador);	
        ModelAndView mav = new ModelAndView();
        mav.setViewName("ficha-cursada");
        mav.addObject("cursada", asignatura);
        return mav;
	}
}
